package cn.itwen.star.graph.core.job;

import cn.hutool.core.date.DateTime;
import cn.itwen.star.graph.comfyui.client.api.ComfyuiApi;
import cn.itwen.star.graph.comfyui.client.pojo.ComfyuiTask;
import cn.itwen.star.graph.core.service.RedisService;
import cn.itwen.star.graph.core.service.UserFundRecordService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Response;

import javax.sound.midi.MidiFileFormat;
import java.io.IOException;
import java.util.HashMap;

@Component
@Slf4j
public class RunTaskJob {

    private static final String SPRING_TASK_LOCK_KEY = "lock:task";
    public final static String TASK_RUN_SEMAPHORE = "TASK_RUN_SEMAPHORE";

    @Autowired
    private RedisService redisService;

    @Autowired
    private ComfyuiApi comfyuiApi;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private UserFundRecordService userFundRecordService;


    @Scheduled(cron = "*/1 * * * * ?")
    public void task(){
        RLock lock = redissonClient.getLock(SPRING_TASK_LOCK_KEY);
        if (lock. tryLock()) {
            try {
                if (redisService.hasQueueTask()) {
                    //尝试获取信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(TASK_RUN_SEMAPHORE);
                    if (semaphore.tryAcquire()) {
                        log.info("获取许可证成功，开始执行任务");
                        addTaskToComfyuiQueue();
                    }
                }
            }finally {
                lock.unlock();
            }
        }
    }

    /**
     * 添加任务到comfyui队列
     */
    private void addTaskToComfyuiQueue(){
        try {
            //1.从redis中获取序号最小的一个任务
            ComfyuiTask task = redisService.popQueueTask();
            if (task == null){
                return;
            }
            //2.调用api将任务发送到comfyui，并获取结果
            Call<HashMap> addQueueTask = comfyuiApi.addQueueTask(task.getComfyuiRequestDto());
            Response<HashMap> response = addQueueTask.execute();
            if (response.isSuccessful()){
                HashMap body = response.body();
                String promptId = body.get("prompt_id").toString();
                //提交任务成功，将任务添加到redis中，用于后续查询结果
                task.setPromptId(promptId);
                log.info("任务成功添加到队列，promptId:{}",promptId);
                redisService.addStartedTask(promptId,task);
            }else {
                String errorMsg = response.errorBody().string();
                log.error("任务添加队列失败，错误信息:{}",errorMsg);
                //积分归还
                userFundRecordService.freezeReturn(task.getUserId(),task.getSize());
                //释放信号量
                RSemaphore semaphore = redissonClient.getSemaphore(TASK_RUN_SEMAPHORE);
                semaphore.release();
            }
        } catch (Exception e) {
            log.error("添加任务到队列失败",e);
        }

    }
}